﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Commons.ViewModels.Chart;
using Atmk.WaterMeter.MIS.Entities.Models;
using NLog;

namespace Atmk.WaterMeter.MIS.Logic.Statistics
{
    public class RegionLogic : IRegionLogic
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly IOwnerRepository _ownerRepository;
        private readonly IMeterRepository _meterRepository;
        private readonly IMeterReadingRepository _meterReadingRepository;
        private readonly IDistrictRepository _districtRepository;

        public RegionLogic(
            IOwnerRepository ownerRepository,
            IMeterRepository meterRepository,
            IMeterReadingRepository meterReadingRepository,
            IDistrictRepository districtRepository
        )
        {
            _ownerRepository = ownerRepository;
            _meterRepository = meterRepository;
            _meterReadingRepository = meterReadingRepository;
            _districtRepository = districtRepository;
        }

        public List<District> GetLeafDistrictEntities(string areaId)
        {
            return _districtRepository.GetLeafDistrictEntities(areaId);
        }

        /// <summary>
        /// 根据项目获取片区统计信息
        /// </summary>
        /// <param name="areaId"></param>
        /// <returns></returns>
        public StatisticsInfoData GetStatisticsInfoData(string areaId)
        {
            //获取片区
            var districts = _districtRepository.GetLeafDistrictEntities(areaId).ToList();
            //获取业主
            var owners = _ownerRepository.GetOwners(districts.Select(d=>d.Id.ToString()).ToArray());
            //获取所有水表
            var meters = _meterRepository.GetMetersByOwnerIds(owners.Select(o => o.Id.ToString()).ToArray());
            //获取抄表数据
            var onlineMeters = _meterReadingRepository.RangeNewDateMeterReadingRecords(
                meters.Select(m => m.MeterNumber).ToList(), DateTime.Now.Date.AddDays(-3), DateTime.Now.Date);
            //水表在线率：近三日抄表记录水表数量，除以总水表数量
            var result = new StatisticsInfoData
            {
                districtCount = districts.Count,
                meterCount = meters.Count,
                ownerCount = owners.Count
            };
            if (onlineMeters != null)
                result.onlineRatio = onlineMeters.Count * 100.00 / meters.Count;
            else
                result.onlineRatio = 0.00;
            return result;
        }
    }
}
